/**  
 * @Title:  MinioConfig.java   
 * @Package com.platform.config   
 * @Description: (用一句话描述该文件做什么)   
 * @author: <a href="mailto:15909910367@163.com">吴先生</a> 
 * @date:   2020年11月13日 下午4:46:46   
 * @version V1.0 
 * @Copyright: 2020 吴先生.
 */
package com.platform.config;

import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import org.hibernate.validator.group.GroupSequenceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.platform.minio.model.MinioProperties;

import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;

/**   
 * @ClassName:  MinioConfig   
 * @Description:连接文件服务器
 * @author: <a href="mailto:15909910367@163.com">吴先生</a>  
 * @date:   2020年11月13日 下午4:46:46   
 *     
 * @Copyright: 2020 吴元森.  
 */
@Configuration
@ConditionalOnClass(MinioClient.class)
@EnableConfigurationProperties(MinioProperties.class)
@SuppressWarnings("all")
public class MinioConfig {
	
	private Logger logger = LoggerFactory.getLogger(MinioConfig.class);
	
	@Value("${minio.buckets}")
	private String buckets;
	
	/**
	 * @Title: initMinioClient   
	 * @Description: 初始化minio
	 * @param minioProperties
	 * @return
	 * @throws InvalidEndpointException
	 * @throws InvalidPortException      
	 * MinioClient
	 */
	@Bean
	public MinioClient initMinioClient(@Autowired MinioProperties minioProperties) throws InvalidEndpointException, InvalidPortException {
		logger.info("\n----------------------------------------------------------\n\t" +
                "系统配置初始化: \t\t装配系统附件管理服务\n" +
                "----------------------------------------------------------");
			MinioClient minioClient = new MinioClient(minioProperties.getUrl(), minioProperties.getAccessKey(), minioProperties.getSecretAccessKey());
			 minioClient.setTimeout(TimeUnit.SECONDS.toMillis(minioProperties.getConnectTimeout()), 
					 TimeUnit.SECONDS.toMillis(minioProperties.getWriteTimeout()),
					 TimeUnit.SECONDS.toMillis(minioProperties.getReadTimeout()));
			//检查bucket是否存在，不存在就创建
			checkBucket(minioClient);
			return minioClient;
	}
	
	/**
	 * @Title: checkBucket   
	 * @Description: 检查节点链路
	 * @param minioClient      
	 * void
	 */
	private void checkBucket(MinioClient minioClient){
		Stream.of(buckets).forEach(bucket ->{
			logger.info("存储节点",bucket);
		});
		try {
			if(minioClient.bucketExists(buckets)) return;
			minioClient.makeBucket(buckets);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
